import axios from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router/index.js";


// 创建 axios 实例
const service = axios.create({
    baseURL: 'http://127.0.0.1:9090/api',
    timeout: 10000,
});

service.interceptors.request.use(
    (config) => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        let user = JSON.parse(localStorage.getItem('user') || '{}');
        if (user?.token) {
            config.headers['Authorization'] = user.token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        if (response.data.code === '10017' || response.data.code === '10018') {
            ElMessage.error("登录已过期，请重新登录");
            localStorage.removeItem('user');
            void router.push('/login')
        }
        return response;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default service;
